package com.central.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.modules.sys.dao.SysRoleUserDao;
import com.central.modules.sys.entity.SysRoleUserEntity;
import com.central.modules.sys.service.SysRoleUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserDao, SysRoleUserEntity> implements SysRoleUserService {



    @Override
    public boolean add(Long userId, List<Long> roleIds) {
        this.cleanByUserId(userId);
        if (!CollectionUtils.isEmpty(roleIds)) {
            this.saveBatch(roleIds.stream().map(roleId -> {
                SysRoleUserEntity roleUserEntity = new SysRoleUserEntity();
                roleUserEntity.setRoleId(roleId);
                roleUserEntity.setUserId(userId);
                return roleUserEntity;
            }).collect(Collectors.toSet()));
        }
        return true;
    }

    @Override
    public boolean cleanByRoleId(Long roleId) {
        QueryWrapper<SysRoleUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRoleUserEntity::getRoleId, roleId);
        return this.remove(queryWrapper);
    }

    @Override
    public boolean cleanByUserId(Long userId) {
        QueryWrapper<SysRoleUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRoleUserEntity::getUserId, userId);
        return this.remove(queryWrapper);
    }

    @Override
    public boolean removeByRoleIdAndUserId(Long roleId, Long userId) {
        QueryWrapper<SysRoleUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRoleUserEntity::getRoleId, roleId).eq(SysRoleUserEntity::getUserId, userId);
        return this.remove(queryWrapper);
    }

    @Override
    public List<Long> listAllByUserId(Long userId) {
        QueryWrapper<SysRoleUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRoleUserEntity::getUserId, userId);
        return this.list(queryWrapper).stream().map(SysRoleUserEntity::getRoleId).collect(Collectors.toList());
    }
}

